package com.haifeng.lyw.jinganghc.bluetooth;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.haifeng.lyw.jinganghc.MyApplication;
import com.haifeng.lyw.jinganghc.R;
import com.haifeng.lyw.jinganghc.adapter.ChatListAdapter;
import com.haifeng.lyw.jinganghc.utils.PermissionsChecker;

import java.util.ArrayList;
import java.util.Set;

public class deviceActivity extends Activity {

    enum ServerOrCilent {
        NONE,
        SERVICE,
        CILENT
    }
    private PermissionsChecker mPermissionsChecker;


    public static final int PERMISSIONS_GRANTED = 0; // 权限授权
    public static final int PERMISSIONS_DENIED = 1; // 权限拒绝
    private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限管理页面的参数
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    static final String[] PERMISSIONS = new String[]{

            Manifest.permission.ACCESS_COARSE_LOCATION,

    };
    private ListView mListView;
    private ArrayList<SiriListItem> list;

    private Button seachButton;
    private TextView tv_more;
    ChatListAdapter mAdapter;
    Context mContext;
//    public clientThread clientConnectThread = null;
    /* 取得默认的蓝牙适配器 */
    private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    static String BlueToothAddress = "null";

//    static boolean isOpen = false;
private MyApplication application;


//    private BluetoothDevice device1;
    @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 3);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.devices);
        mContext = this;
        mPermissionsChecker = new PermissionsChecker(this);
        init();
      initPer();
    }

    private void initPer() {
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {

            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                //请求权限
                ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST_CODE);

            } else {
                Log.i("WWDZ","全部权限都已获取11");
            }
        } else {
            Log.i("WWDZ","全部权限都已获取22");
        }
    }

    private void init() {
        list = new ArrayList<SiriListItem>();


        mAdapter = new ChatListAdapter(this, list);
        mListView = (ListView) findViewById(R.id.list);
        tv_more = findViewById(R.id.tv_more);
        mListView.setAdapter(mAdapter);
        mListView.setFastScrollEnabled(true);
        mListView.setOnItemClickListener(mDeviceClickListener);
        final Button start_test = findViewById(R.id.start_test);
        tv_more.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.flage = !mAdapter.flage;

                if (mAdapter.flage) {
                    tv_more.setText("取消");
                    start_test.setVisibility(View.VISIBLE);
                    seachButton.setVisibility(View.GONE);
                } else {
                    tv_more.setText("多控");
                    start_test.setVisibility(View.GONE);
                    seachButton.setVisibility(View.VISIBLE);
                }

                mAdapter.notifyDataSetChanged();
            }
        });
        start_test.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                btnOperateList();
                connect();
;
            }
        });
        // 当设备被发现时，注册为广播
        IntentFilter discoveryFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, discoveryFilter);

        // 当发现完成时，注册广播
        IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, foundFilter);

        // 获取一组当前成对的设备
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // 如果有成对的设备，将每个设备添加到ArrayAdapter中
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), true));
                mAdapter.notifyDataSetChanged();
                mListView.setSelection(list.size() - 1);
            }
        } else {
            list.add(new SiriListItem("没有设备已经配对", true));
            mAdapter.notifyDataSetChanged();
            mListView.setSelection(list.size() - 1);
        }
        //点击开始搜索周围设备和已经配对的设备，进行配对连接
        seachButton = (Button) findViewById(R.id.start_seach);
        seachButton.setOnClickListener(seachButtonClickListener);

    }

    private OnClickListener seachButtonClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
                seachButton.setText("重新搜索");
            } else {
                list.clear();
                mAdapter.notifyDataSetChanged();

                Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
                if (pairedDevices.size() > 0) {
                    for (BluetoothDevice device : pairedDevices) {
                        list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), true));
                        mAdapter.notifyDataSetChanged();
                        mListView.setSelection(list.size() - 1);
                    }
                } else {
                    list.add(new SiriListItem("No devices have been paired", true));
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
                    /* 开始搜索 */
                mBtAdapter.startDiscovery();
                seachButton.setText("停止搜索");
            }
        }
    };

    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect

            SiriListItem item = list.get(arg2);
            String info = item.message;
            final String address = info.substring(info.length() - 17);
            BlueToothAddress = address;

            AlertDialog.Builder StopDialog = new AlertDialog.Builder(mContext);//定义一个弹出框对象
            StopDialog.setTitle("连接");//标题
            StopDialog.setMessage(item.message);
            StopDialog.setPositiveButton("连接", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    mBtAdapter.cancelDiscovery();
                    seachButton.setText("重新搜索");

                        Common.bleAddrList.add(Common.mBluetoothAdapter.getRemoteDevice(address));

                    Intent intent = new Intent(deviceActivity.this, WorkView.class);
                    startActivity(intent);



                }
            });
            StopDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    BlueToothAddress = null;
                }
            });
            StopDialog.show();
        }
    };
    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    list.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), false));
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                if (mListView.getCount() == 0) {
                    list.add(new SiriListItem("没有发现蓝牙设备", false));
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
                seachButton.setText("重新搜索");
            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
Common.bleAddrList.clear();
        Common.bluetoothGattList.clear();
        Common.mCharacteristic.clear();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("WWDZ", "onDestroy");


        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        this.unregisterReceiver(mReceiver);

    }




    /**
     * 获取选中数据
     */
    public void btnOperateList() {
        if (Common.bleAddrList != null) {
            Common.bleAddrList.clear();
            Common.bleAddrList.clone();
        }


        if (mAdapter.flage) {

            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).isCheck) {

                    String info = list.get(i).message;
                    String address = info.substring(info.length() - 17);
                    Common.bleAddrList.add(Common.mBluetoothAdapter.getRemoteDevice(address));



                }
            }

        }
    }
    private void connect() {
                Intent intent = new Intent(deviceActivity.this, WorkView.class);
                startActivity(intent);
//    for (int i=0;i<Common.bleAddrList.size();i++){
//       Common.bleAddrList.get(i).connectGatt(this, false, coreGattCallback);
//
//    }


    }




    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
            //   initIM();
            Log.i("WWDZ","登陆成功");
        } else {

            showMissingPermissionDialog();
        }
    }

    //含有全部的权限

    private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(deviceActivity.this);
        builder.setTitle("帮助");
        builder.setMessage("当前应用缺少必要权限");

        // 拒绝, 退出应用
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.show();
    }
    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //TODO something

            System.exit(0);
                //退出时杀掉所有进程
                android.os.Process.killProcess(android.os.Process.myPid());

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}